import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, List, Button, Tag, Typography, message, Spin, Space } from 'antd';
import { ClockCircleOutlined, FileTextOutlined, PlayCircleOutlined, TrophyOutlined } from '@ant-design/icons';
import { InfoCard } from '@/components/common';
import { questionService } from '@/services/questionService';
import { PaperListItem, PaperStatus } from '@/types/question';

const { Title, Text } = Typography;

const PaperList: React.FC = () => {
  const navigate = useNavigate();
  const [papers, setPapers] = useState<PaperListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取试卷列表（新问卷系统）
  const fetchPapers = async (page = 1, pageSize = 10) => {
    try {
      setLoading(true);
      const response = await questionService.getPapers({
        page,
        limit: pageSize,
        status: PaperStatus.PUBLISHED,  // 只显示已发布的试卷
      });

      const data = response.data.data;
      setPapers(data.results || []);
      setPagination({
        current: page,
        pageSize,
        total: data.count || 0,
      });
    } catch (error) {
      console.error('获取试卷列表失败:', error);
      message.error('获取试卷列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPapers();
  }, []);

  // 开始答题
  const handleStartExam = (paperId: number) => {
    navigate(`/client/paper/exam/${paperId}`);
  };

  // 格式化时长
  const formatDuration = (minutes: number) => {
    if (minutes < 60) {
      return `${minutes} 分钟`;
    }
    const hours = Math.floor(minutes / 60);
    const remainingMinutes = minutes % 60;
    return remainingMinutes > 0 ? `${hours} 小时 ${remainingMinutes} 分钟` : `${hours} 小时`;
  };

  // 获取试卷状态标签
  const getPaperStatusTag = (paper: PaperListItem) => {
    if (paper.status === 'draft') {
      return <Tag color="default">草稿</Tag>;
    } else if (paper.status === 'ended') {
      return <Tag color="red">已结束</Tag>;
    }
    
    if (!paper.start_time || !paper.end_time) {
      return <Tag color="green">可答题</Tag>;
    }
    
    const now = new Date();
    const startTime = new Date(paper.start_time);
    const endTime = new Date(paper.end_time);

    if (now < startTime) {
      return <Tag color="blue">未开始</Tag>;
    } else if (now > endTime) {
      return <Tag color="red">已结束</Tag>;
    } else {
      return <Tag color="green">进行中</Tag>;
    }
  };

  // 判断是否可以参加考试
  const canTakeExam = (paper: PaperListItem) => {
    if (paper.status !== 'published') {
      return false;
    }
    
    if (!paper.start_time || !paper.end_time) {
      return true;  // 没有时间限制，可以答题
    }
    
    const now = new Date();
    const startTime = new Date(paper.start_time);
    const endTime = new Date(paper.end_time);
    return now >= startTime && now <= endTime;
  };

  return (
    <InfoCard
      title={
        <Space>
          <FileTextOutlined />
          试卷列表
        </Space>
      }
      extra={<Text type="secondary">选择试卷开始答题</Text>}
    >
      <Spin spinning={loading}>
        <List
          grid={{ gutter: 16, column: 1 }}
          dataSource={papers}
          pagination={{
            ...pagination,
            onChange: (page, pageSize) => fetchPapers(page, pageSize),
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
          renderItem={(paper) => (
            <List.Item>
              <Card
                title={
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span>{paper.title}</span>
                    {getPaperStatusTag(paper)}
                  </div>
                }
                extra={
                  <Button
                    type="primary"
                    icon={<PlayCircleOutlined />}
                    disabled={!canTakeExam(paper)}
                    onClick={() => handleStartExam(paper.id)}
                  >
                    开始答题
                  </Button>
                }
              >
                <div>
                  <Space direction="vertical" style={{ width: '100%' }} size="middle">
                    <div>
                      <Space size="large" wrap>
                        <Space>
                          <ClockCircleOutlined />
                          <span>时长：{formatDuration(paper.duration)}</span>
                        </Space>
                        <Space>
                          <FileTextOutlined />
                          <span>题目：{paper.question_count || 0} 道</span>
                        </Space>
                        <Space>
                          <TrophyOutlined />
                          <span>总分：{paper.total_score} 分</span>
                        </Space>
                      </Space>
                    </div>
                    
                    {(paper.start_time || paper.end_time) && (
                      <div style={{ color: '#666', fontSize: '13px' }}>
                        {paper.start_time && (
                          <div>开始时间：{new Date(paper.start_time).toLocaleString('zh-CN')}</div>
                        )}
                        {paper.end_time && (
                          <div>结束时间：{new Date(paper.end_time).toLocaleString('zh-CN')}</div>
                        )}
                      </div>
                    )}
                    
                    {paper.description && (
                      <div>
                        <Text type="secondary">{paper.description}</Text>
                      </div>
                    )}
                    
                    <div>
                      <Space size="small">
                        <Tag color="blue">{paper.submit_count || 0} 人已参加</Tag>
                        <Tag color="orange">及格分：{paper.passing_score}</Tag>
                      </Space>
                    </div>
                  </Space>
                </div>
              </Card>
            </List.Item>
          )}
        />
      </Spin>
    </InfoCard>
  );
};

export default PaperList; 